# coding:utf-8
import functools

import cv2
import os
import numpy as np
import time

from appium import webdriver
from appium.webdriver.common.touch_action import TouchAction
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions
from selenium.webdriver.support.wait import WebDriverWait

def sendkeyByTouch(driver,content):
    ''' 数字键盘定位 输入
    1   ,  200,1100
    2   -   500,1100
    3   -   800,1100
    4   -   200,1250
    5   -   500,1250
    6  -   800,1250
    7  -   200,1400
    8  -   500,1400
    9  -   800,1400
    0  - 500,1500
    '''
    num_keys ={ '1' :[200,1100] ,
                '2' :[500,1100]  ,
                '3' :[800,1100]  ,
                '4' :[200,1250]  ,
                '5' :[500,1250]  ,
                '6' :[800,1250]  ,
                '7' :[200,1400]  ,
                '8' :[500,1400]  ,
                '9' :[800,1400]  ,
                '0' :[500,1500]}
    time.sleep(1)
    for n in content:
        # print(num_keys[n][0])
        # print(num_keys[n][1])
        TouchAction(driver).tap(x=num_keys[n][0], y=num_keys[n][1]).wait(300).perform()
    # 按确定
    TouchAction(driver).tap(x=800, y=980).wait(300).perform()
    time.sleep(0.5)



class gesture_mainpulation:
    '''
    description:手势操作
    '''
    def __init__(self,driver):
        self.drv = driver
        self.win_width =driver.get_window_size()['width']
        self.win_height = driver.get_window_size()['height']


    def swipe_left(self):
        '''左滑'''
        x = self.win_width
        y = self.win_height
        self.drv.swipe(x*3/4,y/4,x/4,y/4)

    def swipe_right(self):
        '''右滑'''
        x = self.win_width
        y = self.win_height
        self.drv.swipe(x/4,y/4,x*3/4,y/4)

    def swipe_down(self):
        '''下滑'''
        x = self.win_width
        y = self.win_height
        self.drv.swipe(x/2,y*3/4,x/2,y/4)

    def swipe_down_all(self):
        '''下滑'''
        x = self.win_width
        y = self.win_height
        # self.drv.swipe(x/2,y*5/6,x/2,y*2/3)
        # TouchAction(self.drv).press(x=x//2, y=y*5//6).wait(300).move_to(x=x//2, y=y*2//6).wait(300).release().perform()

        TouchAction(self.drv).press(x=435, y=1025).wait(300).move_to(x=446, y=600).release().perform()

    def swipe_up(self):
        '''上滑'''
        x = self.win_width
        y = self.win_height
        self.drv.swipe(x/2,y/4,x/2,y*3/4)

def get_pay_keyboard_number_location(im, pwd):
    numbers = set(list(pwd))
    templates = {}
    positions = {}
    nimgpath = ""   #数字图片不在同目录时使用
    for i in numbers:
        templates[i]  = os.path.join(nimgpath, "n{}.jpg".format(i))

    start = time.time()
    img_rgb = cv2.imread(im)
    for teNum, tepath in templates.items():
        # print(tepath)
        template = cv2.imread(tepath)
        h, w = template.shape[:-1]

        res = cv2.matchTemplate(img_rgb, template, cv2.TM_CCOEFF_NORMED)
        threshold = .95    # 匹配度参数，1为完全匹配
        loc = np.where(res >= threshold)
        if len(loc) > 0:
            positions[teNum] = zip(*loc[::-1])[0]
        else:
            print("Can not found number: [{}] in image: [{}].".format(tepath, im))

    end = time.time()
    print(end-start)

    return [positions[n] for n in pwd]



def back_toElement(driver, by=By.ID, locator=''):
    '''
    返回按钮，直到找到指定元素
    :param driver:
    :param by:
    :param locator:
    :return:
    '''

    for i in range(5):
        if isElementExist(driver, by, locator,time=0.5):
            return driver.find_element(by, locator)
        # 返回
        driver.back()
        time.sleep(0.3)

def checkElement_click(driver, by=By.ID, locator='',time=5):
    '''
    检查元素是否存在，并 click
    :param driver:
    :param by:
    :param locator:
    :return:
    '''
    wait_element(driver, locator, by, time)

    els1=None
    try:
        els1 = driver.find_element(by, locator)
            # driver.find_element_by_id("com.rong360.app:id/btn3_tv")
        if els1!=None :
            els1.click()
    except Exception as identifier:
        pass

def isElementExist(driver, by=By.ID, locator='',time=1):
    '''
    *判断元素是否存在，存在返回true，用在断言的判断，如登录成功了要判断这个界面上某个元素是否存在，如果存在为成功否则为失败，不需要对这个元素进行操作用这种方式
    #     * 如果需要操作，需返回AndroidElement
    #     * @param by
    #     * @return
    '''
    try:
        if time>0 : wait_element(driver, locator, by, time)

        driver.find_element(by, locator)
        return True
    except Exception as e:
        return False


def wait_element(driver, locator, by=By.ID, time=10, msg=''):
    """
    等待元素出现
    调用
    # wait_element(deriver, "com.xxx.xxx.ceshi:id/main_select_index_rb",By.ID, 10,  "没有发现xxxx...")
    :param driver: driver
    :param time: 等待时间
    :param by: 元素类型
    :param locator: 元素关键字
    :param msg: 输出信息
    :return:
    """
    try:
        driver.implicitly_wait(0)
        return WebDriverWait(driver, time).\
            until(expected_conditions.presence_of_element_located((by, locator)), msg)

    except Exception:
        return None
    finally:
        driver.implicitly_wait(3)

def waitElement_click(driver, by=By.ID, locator='', time=10, msg=''):
    '''
    等待元素出现后，点击
    :param driver:
    :param locator:
    :param by:
    :param time:
    :param msg:
    :return:
    '''
    element = wait_element(driver,locator,by,time,msg)
    if element!=None: element.click()


def swipe_toElement(driver, by=By.ID, locator='', count=20):
    '''
    滚动到指定元素
    swipe_toElement(driver,By.XPATH,"//android.widget.TextView[contains(@text,'%s')]"% toText)
    :param driver: webdriver
    :param by:     By 定位类型
    :param locator:  定位串
    :param count:  滚动次数
    :return: 返回元素 element
    '''
    for i in range(count):   #向上 滑动屏幕20次
        # time.sleep(0.5)

        if isElementExist(driver, by, locator,time=0.1):
            print('--->>>找到 ' + locator)
            return driver.find_element(by, locator)

        TouchAction(driver).press(x=435, y=1025).wait(300).move_to(x=446, y=700).release().perform()
        print('>>>滑动 ' + str(i))
    else:
        print('<<<没找到 ' + locator)
        return None

        # els1=None
        # try:
        #     els1 = driver.find_elements_by_xpath("//android.widget.TextView[contains(@text,'%s')]"% toText)
        #     # driver.find_elements_by_AndroidUIAutomator("className(\"android.widget.TextView\").text(\"省心贷\")")
        #     if els1!=None :
        #         els1[0].click()
        #         print('进入 ==>'+toText)
        #         time.sleep(1)
        #         break
        # except Exception as identifier:
        #     print('没找到 '+toText)




if __name__ == "__main__":
    # ls = get_pay_keyboard_number_location('D:\test\img\sekeyboard.png', '123456')
    # print(ls)

    # sendkeyByTouch('01283409')
    pass



# /**
#     * 逐个输入数字，模拟的是键盘数字输入，13082834445
#     * @param text 传入的数字
#     */
# public void sendMobileNumber(String text) {
#     char[] chr=text.toCharArray();//把字符串拆成字符数组{1,2,3,5,x,x,x}
#     //因为每个都需要输入所以加循环
#     for(int i=0;i<chr.length;i++){
#         int c=Integer.valueOf(String.valueOf(chr[i]));//先把字符转换字符串，再把字符串转换成数字
#         int number=0;
#         switch (c) {
#         case 0:
#             //driver.pressKeyCode(AndroidKeyCode.KEYCODE_0);
#             number=AndroidKeyCode.KEYCODE_0;
#             break;
#         case 1:
#             number=AndroidKeyCode.KEYCODE_1;
#             break;
#         case 2:
#             number=AndroidKeyCode.KEYCODE_2;
#             break;
#         case 3:
#             number=AndroidKeyCode.KEYCODE_3;
#             break;
#         case 4:
#             number=AndroidKeyCode.KEYCODE_4;
#             break;
#         case 5:
#             number=AndroidKeyCode.KEYCODE_5;
#             break;
#         case 6:
#             number=AndroidKeyCode.KEYCODE_6;
#             break;
#         case 7:
#             number=AndroidKeyCode.KEYCODE_7;
#             break;
#         case 8:
#             number=AndroidKeyCode.KEYCODE_8;
#             break;
#         case 9:
#             number=AndroidKeyCode.KEYCODE_9;
#             break;
#         default:
#             System.out.println("数值不对");
#             break;
#         }
#         driver.pressKeyCode(number);
#     }
# }
